package main.com.votes.dao;

import main.com.votes.model.Article;
import main.com.votes.utils.ConnDB;

import javax.servlet.http.HttpServletRequest;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

public class ArticleDao extends BaseDAO{

//    已投票人数

    public int getVoteCount(int articleid){
        String sql = "SELECT count(*) FROM vote WHERE articleid=?";
        ResultSet set = ConnDB.executeQuery(sql, new Object[]{articleid});
        try {
            if (set.next()) {
                try {
                    return set.getInt(1);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return 0;
    }

//    全部投票项目
    public List<Article> getArticles() {
        String sql = "select * from article";
        return super.selectAll(sql, new Object[]{});
    }

    //    添加投票项目
    public int addArticle(String title, String type, HttpServletRequest httpServletRequest) {
        String sql = "insert into article values(0,?,?,?,?)";
        return super.update(sql, new Object[]{title, type, LocalDateTime.now(),
                httpServletRequest.getSession().getAttribute("userId")});
    }

//    获取某个投票项目
public Article getOne(String title, String type) {
    String sql = "select * from article  where title=? and type=?";
    return super.select(sql, new Object[]{title, type});
}


    @Override
    public Article rowMapper(ResultSet rs) throws SQLException {
        Article article = new Article(
                rs.getInt(1),
                rs.getString(2),
                rs.getInt(3),
                rs.getTimestamp(4),0,0,
                rs.getInt(5)
        );
        return article;
    }

    public Article getById(int articleid) {
        String sql = "select * from article where id=?";
        return super.select(sql, new Object[]{articleid});
    }

    public List<Article> selectByTitle(String key) {
//        根据投票项目名查询
        String sql = "select * from article where title like ?";
        return super.selectAll(sql, new Object[]{"%"+key+"%"});
    }

    public List<Article> selectCreateByMe(HttpServletRequest request) {
        String sql = "SELECT * FROM article\n" +
                "WHERE userId=?";
        return super.selectAll(sql, new Object[]{request.getSession().getAttribute("userId")});
    }

    public int deleteArticle(String articleId) {
        String sql = "delete from article where id=?";
        return super.update(sql, new Object[]{articleId});
    }
}
